<template>
  <div class="calls-container">
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 顶部搜索栏 -->
      <div class="search-bar">
        <div class="search-input">
          <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" fill="#666"/>
          </svg>
          <input 
            type="text" 
            placeholder="Find contact, call ..." 
            class="search-field" 
            v-model="searchQuery"
          />
        </div>
      </div>

      <!-- 标题和操作按钮 -->
      <div class="header">
        <h1 class="page-title">Calls</h1>
        <div class="header-actions">
          <button class="action-btn" @click="startNewCall">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z" fill="#666"/>
            </svg>
          </button>
          <button class="action-btn">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="#666"/>
            </svg>
          </button>
        </div>
      </div>

      <!-- 通话记录内容 -->
      <div class="calls-content">
        <!-- 有通话记录时显示列表 -->
        <div v-if="callHistory.length > 0" class="calls-list">
          <div 
            v-for="call in filteredCalls" 
            :key="call.id" 
            class="call-item"
            @click="makeCallFromHistory(call)"
          >
            <div class="call-avatar">
              <span class="avatar-text">{{ getAvatarText(call.target_display) }}</span>
            </div>
            <div class="call-info">
              <div class="call-name">{{ call.target_display }}</div>
              <div class="call-details">
                <span class="call-type-icon" :class="getCallTypeClass(call.call_type)">
                  {{ getCallTypeIcon(call.call_type) }}
                </span>
                <span class="call-time">{{ formatCallTime(call.timestamp) }}</span>
              </div>
            </div>
            <div class="call-action">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z" fill="#666"/>
              </svg>
            </div>
          </div>
        </div>
        
        <!-- 无通话记录时显示空状态 -->
        <div v-else class="no-calls">
          <p class="no-calls-text">No call in history</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CallsPage',
  data() {
    return {
      callHistory: [],
      searchQuery: ''
    }
  },
  computed: {
    filteredCalls() {
      if (!this.searchQuery) {
        return this.callHistory;
      }
      const query = this.searchQuery.toLowerCase();
      return this.callHistory.filter(call => 
        call.target_display.toLowerCase().includes(query) ||
        call.target.toLowerCase().includes(query)
      );
    }
  },
  async mounted() {
    await this.loadCallHistory();
  },
  methods: {
    startNewCall() {
      this.$router.push({ name: 'NewCall' });
    },
    async loadCallHistory() {
      try {
        const { invoke } = window.__TAURI__.core;
        this.callHistory = await invoke('get_call_history');
        // 按时间戳倒序排列（最新的在前）
        this.callHistory.sort((a, b) => b.timestamp - a.timestamp);
      } catch (error) {
        console.error('加载通话记录失败:', error);
        this.callHistory = [];
      }
    },
    getAvatarText(displayName) {
      if (!displayName) return '?';
      // 如果是纯数字，取第一个数字
      if (/^\d+$/.test(displayName)) {
        return displayName[0];
      }
      // 如果是Extension格式，取E+第一个数字
      if (displayName.toLowerCase().startsWith('extension')) {
        const match = displayName.match(/\d+/);
        return match ? `E${match[0][0]}` : 'E';
      }
      // 其他情况取前两个字符
      return displayName.substring(0, 2).toUpperCase();
    },
    getCallTypeIcon(callType) {
      switch (callType) {
        case 'Outgoing':
          return '↗'; // 红色向上箭头
        case 'Incoming':
          return '✓'; // 绿色勾号
        case 'Missed':
          return '↘'; // 蓝色向下箭头
        default:
          return '?';
      }
    },
    getCallTypeClass(callType) {
      switch (callType) {
        case 'Outgoing':
          return 'outgoing';
        case 'Incoming':
          return 'incoming';
        case 'Missed':
          return 'missed';
        default:
          return '';
      }
    },
    formatCallTime(timestamp) {
      const date = new Date(timestamp);
      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const callDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      
      if (callDate.getTime() === today.getTime()) {
        // 今天
        return `Today | ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`;
      } else {
        // 其他日期
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const time = date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        return `${month} 月 ${day} 日 | ${time}`;
      }
    },
    makeCallFromHistory(call) {
      // 跳转到拨号页面并预填号码
      this.$router.push({ 
        name: 'NewCall',
        query: { number: call.target }
      });
    }
  }
}
</script>

<style scoped>
.calls-container {
  height: 100%;
  background: #fff;
  display: flex;
  flex-direction: column;
  min-height: 0;
}



/* 主内容区域 */
.main-content {
  flex: 1;
  padding: 30px;
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 0;
}

/* 搜索栏 */
.search-bar {
  margin-bottom: 30px;
}

.search-input {
  position: relative;
  max-width: 100%;
}

.search-icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
}

.search-field {
  width: 100%;
  padding: 15px 15px 15px 45px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  font-size: 14px;
  background: #f8f9fa;
  outline: none;
  transition: border-color 0.3s ease;
}

.search-field:focus {
  border-color: #ff6b35;
  background: white;
}

.search-field::placeholder {
  color: #666;
}

/* 标题和操作按钮 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.action-btn {
  width: 48px;
  height: 48px;
  border: none;
  border-radius: 12px;
  background: #f8f9fa;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s ease;
}

.action-btn:hover {
  background: #e9ecef;
}

/* 通话记录内容 */
.calls-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.calls-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 5px;
}

.call-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.call-item:hover {
  background-color: #f8f9fa;
}

.call-item:last-child {
  border-bottom: none;
}

.call-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #e3f2fd;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  flex-shrink: 0;
}

.avatar-text {
  color: #1976d2;
  font-weight: 600;
  font-size: 16px;
}

.call-info {
  flex: 1;
  min-width: 0;
}

.call-name {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 4px;
}

.call-details {
  display: flex;
  align-items: center;
  gap: 8px;
}

.call-type-icon {
  font-size: 14px;
  font-weight: bold;
}

.call-type-icon.outgoing {
  color: #f44336;
}

.call-type-icon.incoming {
  color: #4caf50;
}

.call-type-icon.missed {
  color: #2196f3;
}

.call-time {
  font-size: 14px;
  color: #666;
}

.call-action {
  padding: 8px;
  border-radius: 50%;
  transition: background-color 0.2s ease;
}

.call-action:hover {
  background-color: #e9ecef;
}

.no-calls {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.no-calls-text {
  font-size: 18px;
  color: #1a1a1a;
  font-weight: 500;
  margin: 0;
}
</style>
